// Learn TypeScript:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

import RigidBodyType = cc.RigidBodyType;

const {ccclass, property} = cc._decorator;

@ccclass
export default class Add_physics extends cc.Component {

    @property(cc.Node)
    test: cc.Node = null;

    ctx = null;

    onLoad () {
        cc.director.getPhysicsManager().enabled = true;
        cc.director.getPhysicsManager().debugDrawFlags = 1;

        let width = this.node.width;
        let height = this.node.height;
        let node = new cc.Node();

        let body = node.addComponent(cc.RigidBody);
        body.type = cc.RigidBodyType.Static;

        this.addBound(node, 0, height/2, width, 20);
        this.addBound(node, 0, -height/2, width, 20);
        this.addBound(node, -width/2, 0, 20, height);
        this.addBound(node, width/2, 0, 20, height);

        node.parent = this.node;

        this.node.on("touchmove", this.touch, this);
    }

    start () {
        this.ctx = this.node.getComponent(cc.Graphics);
        this.ctx.moveTo(0, 0);
        this.ctx.lineTo(200, 0);
        this.ctx.stroke();
    }

    touch(e){
        this.ctx.clear();
        let pos = e.getLocation();
        pos = this.node.convertToNodeSpaceAR(pos);
        // console.log(pos.x, pos.y);
        this.ctx.moveTo(pos.x, pos.y);
        this.ctx.circle(pos.x, pos.y, 5);
        this.ctx.fill();
        this.ctx.moveTo(0, 0);
        this.ctx.lineTo(pos.x, pos.y);
        this.ctx.stroke();

        let newVec = pos.sub(cc.v2(0,0));
        let re = cc.v2(1, 0).angle(newVec);
        let angle = re *180 / Math.PI;
        if(pos.y <= 0){
            angle = -angle;
        }
        // console.log(angle);
        this.test.angle = angle
    }

    addBound (node, x, y, width, height) {
        let box = node.addComponent(cc.PhysicsBoxCollider);
        box.offset.x = x;
        box.offset.y = y;
        box.size.width = width;
        box.size.height = height;
    }

    // update (dt) {}
}
